package vfs.common.command.remote;

import vfs.common.command.AbstractCommand;
import vfs.common.file.VirtualFile;
import vfs.common.file.VirtualFileNotFoundException;

import java.util.Map;

/**
 * User: serge
 * Date: 22.11.13
 * Time: 5:10
 */
public class PrintCommand extends AbstractCommand implements RemoteCommand
{
    private String tree = "";

    @Override
    public void execute()
    {
        checkTty();
        checkUser();
        checkFilesystem();

        try
        {
            VirtualFile root = filesystem.locateFile("c:\\", false, user);

            tree += root.getName().concat("\n\r");

            printDir(root, 1);
        }
        catch (VirtualFileNotFoundException e)
        {
            e.printStackTrace();  //Todo generated catch
        }

        tty.send(tree,user);
    }

    /** iterating above the tree recursively */
    private void printDir(VirtualFile dir, int depth)
    {
        for (Map.Entry<String, VirtualFile> fileEntry : dir.getData().entrySet())
        {
            String branch = "";

            for (int i = 0; i < depth; i++)
            {
                /* print '__' before file name */
                branch += (i == depth - 1) ? "|__" : "|  ";
            }

            VirtualFile file = fileEntry.getValue();
            branch += file.getName().concat("\n\r");
            tree += branch;

            if (file.isD())
            {
                printDir(file, depth + 1);
            }
        }
    }
}
